import { ref } from "vue";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";
import { getCustomerList } from "@/api/customer/customer.api";
import { debounce, get } from "lodash-es";

export const useCustomerModal = () => {
  const actionType = ref<ActionTypeEnum>(ActionTypeEnum.ADD);
  const modalShowFlag = ref(false);

  const handleShowModal = () => {
    modalShowFlag.value = true;
  };

  const handleHideModal = () => {
    modalShowFlag.value = false;
  };

  return {
    actionType,
    modalShowFlag,
    handleShowModal,
    handleHideModal,
  };
};

export const useSearchCustomers = () => {
  const customersList = ref<any[]>([]);
  const customerSearchLoading = ref<boolean>(false);

  const handleSearchCustomer = debounce(async function (keyword: string) {
    if (keyword) {
      try {
        customerSearchLoading.value = true;
        const res = await getCustomerList({
          name: `*${keyword}*`,
          pageNo: 1,
          pageSize: 100,
        });
        customersList.value = get(res, "result.records") || [];
      } finally {
        customerSearchLoading.value = false;
      }
    }
  }, 200);

  return { customersList, customerSearchLoading, handleSearchCustomer };
};
